import java.util.Stack;

public class CheckValidString {

    public static void main(String[] args) {
        CheckValidString checkValidString = new CheckValidString();
        System.out.println(checkValidString.checkValidString("((((()(()()()*()(((((*)()*(**(())))))(())()())(((())())())))))))(((((())*)))()))(()((*()*(*)))(*)()"));
    }

    public boolean checkValidString1(String s) {
        int count = 0;
        int sum = 0;
        char[] chars = s.toCharArray();
        int index = -1;
        for (int i = 0; i < chars.length; ++i) {
            char c = chars[i];
            if (c == '(') {
                ++sum;
            } else if (c == ')') {
                --sum;
            } else {
                ++count;
            }
            if (sum == -1) {
                if (count > 0) {
                    sum = 0;
                    --count;
                } else return false;
            }
            if (sum == 0) index = i;
        }
        if (sum == 0) return true;
        sum = 0;
        count = 0;
        for (int i = chars.length - 1; i > index; i--) {
            char c = chars[i];
            if (c == '(') {
                ++sum;
            } else if (c == ')') {
                --sum;
            } else {
                ++count;
            }
            if (sum == 1) {
                if (count > 0) {
                    sum = 0;
                    --count;
                } else return false;
            }
        }
        return sum == 0;
    }

    public boolean checkValidString2(String s) {
        char[] chars = s.toCharArray();
        Stack<Integer> stack = new Stack<>();
        Stack<Integer> stackStar = new Stack<>();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '(') {
                stack.add(i);
            } else if (c == '*') {
                stackStar.add(i);
            } else {
                if (stack.isEmpty()) {
                    if (stackStar.isEmpty()) return false;
                    stackStar.pop();
                } else stack.pop();
            }
        }
        while (!stack.isEmpty() && !stackStar.isEmpty()) {
            if (stack.pop() >= stackStar.pop()) return false;
        }
        return stack.isEmpty();
    }

    public boolean checkValidString(String s) {
        int maxL = 0;
        int minL = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '(') {
                maxL++;
                minL++;
            } else if (c == ')') {
                maxL--;
                minL = Math.max(minL - 1, 0);
                if (maxL < 0) return false;
            } else {
                maxL++;
                minL = Math.max(minL - 1, 0);
            }
        }
        return minL == 0;
    }
}
